import { useRef, useState } from 'react';

import { PlusOutlined, ReloadOutlined, SettingOutlined } from '@ant-design/icons';

import {
  systemRoleListApi,
  systemRoleDeleteApi,
  systemRoleSaveOrUpdateApi,
  type SysRoleItem,
} from '@/api/systemRoleApi';
import type { OperationType } from '@/constants';
import { OperationTypeList, EnableStatusType } from '@/constants';
import { TableLocalePresets } from '@/utils/tableUtils';

import SystemRoleAddForm from './modules/add';

import type { ActionType, ProColumns } from '@ant-design/pro-components';

/**
 * 系统角色管理页面
 * 提供角色的增删改查功能，包括角色列表展示、新增角色、编辑角色、删除角色等操作
 */

/**
 * 扩展的角色项接口
 * 在基础 SysRoleItem 基础上添加表单和UI需要的字段
 */
interface ExtendedRoleItem extends SysRoleItem {
  /** 权限ID数组，用于权限树选择 */
  permissionIdArray?: number[];
}

/**
 * 系统角色管理主组件
 */
const SystemRole = () => {
  // 表格操作引用
  const actionRef = useRef<ActionType>(null);
  // 表单实例
  const [form] = AForm.useForm();

  // 抽屉显示状态
  const [drawerShow, setDrawerShow] = useState(false);
  // 抽屉操作类型（新增/编辑/详情）
  const [drawerType, setDrawerType] = useState<OperationType>('ADD');
  // 当前操作的记录数据
  const [currentRecord, setCurrentRecord] = useState<SysRoleItem>({} as SysRoleItem);

  /**
   * ProTable 数据请求函数
   * @param params 查询参数，包含分页、筛选等信息
   * @returns 返回符合 ProTable 要求的数据格式
   */
  const fetchData = async (params: Record<string, unknown>) => {
    try {
      // 过滤掉无效参数（undefined、null、空字符串）
      const validParams = Object.entries(params).reduce(
        (acc, [key, value]) => {
          if (value !== undefined && value !== null && value !== '') {
            acc[key] = value;
          }
          return acc;
        },
        {} as Record<string, unknown>
      );

      const res = await systemRoleListApi({
        ...validParams,
        page: validParams.current,
      });

      // 检查API响应是否成功
      if (!res || !res.success) {
        window.$message.error(res?.message || '获取角色列表失败');
        return {
          success: false,
          data: [],
          total: 0,
        };
      }

      // 类型断言并提取数据
      const responseData = res.data;
      return {
        success: true,
        data: responseData.records,
        total: responseData?.total ?? 0,
      };
    } catch (error) {
      console.error('获取角色列表失败:', error);
      window.$message.error('获取角色列表失败，请稍后重试');
      return {
        success: false,
        data: [],
        total: 0,
      };
    }
  };

  /**
   * 删除角色处理函数
   * @param record 要删除的角色记录
   */
  const handleDelete = async (record: SysRoleItem) => {
    // 参数验证
    if (!record || !record.id) {
      window.$message.error('删除失败：角色ID不存在');
      return;
    }

    try {
      const res = await systemRoleDeleteApi({ id: record.id });
      if (res.success) {
        window.$message.success('删除成功');
        // 刷新表格数据
        actionRef.current?.reload();
      } else {
        window.$message.error(res.message || '删除失败');
      }
    } catch (error) {
      console.error('删除角色失败:', error);
      window.$message.error('删除失败，请稍后重试');
    }
  };

  /**
   * ProTable 表格列配置
   * 定义表格的列结构、搜索条件、渲染方式等
   */
  const columns: ProColumns<SysRoleItem>[] = [
    {
      title: '角色名称',
      dataIndex: 'name',
      key: 'name',
      copyable: false,
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
      search: false,
      ellipsis: true,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      valueEnum: {
        [EnableStatusType.ENABLED.value]: {
          text: EnableStatusType.ENABLED.label,
          status: 'Success',
        },
        [EnableStatusType.DISABLED.value]: {
          text: EnableStatusType.DISABLED.label,
          status: 'Error',
        },
      },
      render: (_, record) => (
        <ATag color={record.status === EnableStatusType.ENABLED.value ? 'blue' : 'red'}>
          {record.status === EnableStatusType.ENABLED.value
            ? EnableStatusType.ENABLED.label
            : EnableStatusType.DISABLED.label}
        </ATag>
      ),
    },
    {
      title: '操作',
      key: 'action',
      width: 200,
      fixed: 'right',
      search: false,
      render: (_, record) => (
        <ASpace size="small">
          <AButton
            type="link"
            size="small"
            onClick={() => {
              if (record.id) {
                // 处理权限ID字符串转数组
                let permissionIdArray: number[] = [];
                if (record.permissionIds) {
                  try {
                    permissionIdArray = record.permissionIds
                      .split(',')
                      .map(id => Number(id.trim()))
                      .filter(id => !isNaN(id));
                  } catch (error) {
                    console.error('解析权限ID失败:', error);
                  }
                }

                const formData: ExtendedRoleItem = {
                  ...record,
                  permissionIdArray,
                };

                setCurrentRecord(formData);
                setDrawerType('EDIT');
                setDrawerShow(true);
                form.setFieldsValue(formData);
              }
            }}
          >
            编辑
          </AButton>
          <APopconfirm
            title="您确定要删除吗？"
            description={`请确认删除角色【${record.name || ''}】`}
            onConfirm={() => {
              handleDelete(record);
            }}
            okType="danger"
            okText="确认"
            cancelText="取消"
          >
            <AButton type="link" size="small" danger>
              删除
            </AButton>
          </APopconfirm>
        </ASpace>
      ),
    },
  ];

  /**
   * 关闭抽屉并重置状态
   */
  const handleDrawerClose = () => {
    setCurrentRecord({} as ExtendedRoleItem);
    setDrawerType('ADD');
    setDrawerShow(false);
  };

  /**
   * 表单提交处理函数
   * 处理新增和编辑角色的表单提交
   */
  const handleSubmit = async () => {
    try {
      // 表单验证
      const params = await form.validateFields();
      const newParams = {
        ...currentRecord,
        ...params,
      };

      // 处理权限ID数组，转换为后端需要的字符串格式
      if (newParams.permissionIdArray && Array.isArray(newParams.permissionIdArray)) {
        newParams.permissionIds = newParams.permissionIdArray.join(',');
      }

      // 调用保存或更新API
      const res = await systemRoleSaveOrUpdateApi(newParams);
      if (res.success) {
        window.$message.success(drawerType === 'ADD' ? '添加成功' : '更新成功');
        handleDrawerClose();
        actionRef.current?.reload(); // 刷新表格数据
      } else {
        window.$message.error(res.message || '操作失败');
      }
    } catch (error) {
      console.error('表单提交失败:', error);
      window.$message.error('表单验证失败，请检查输入');
    }
  };

  return (
    <div className="page-wrapper">
      <ADrawer
        destroyOnHidden
        title={`角色${OperationTypeList[drawerType].label}`}
        width={600}
        closable={{ 'aria-label': 'Close Button' }}
        footer={
          <ARow justify="end">
            <ASpace>
              <AButton
                onClick={() => {
                  setDrawerShow(false);
                }}
              >
                返回
              </AButton>
              {drawerType !== 'DETAIL' && (
                <AButton type="primary" onClick={handleSubmit}>
                  提交
                </AButton>
              )}
            </ASpace>
          </ARow>
        }
        onClose={handleDrawerClose}
        open={drawerShow}
      >
        <div className="w-full px-8 py-8">
          <AForm form={form} layout="vertical" labelAlign="right" labelCol={{ span: 12 }}>
            <SystemRoleAddForm form={form} data={currentRecord as SysRoleItem} />
          </AForm>
        </div>
      </ADrawer>
      <div className="page-title">
        <div className="page-main-title">角色管理</div>
        <div className="page-sub-title">管理系统角色，配置角色权限和状态</div>
      </div>
      <div className="page-content-box">
        <div className="page-content flex show-bg">
          <div className="w-full">
            <PProTable<SysRoleItem>
              className="mh-table"
              actionRef={actionRef}
              columns={columns}
              request={fetchData}
              rowKey="id"
              search={{
                span: 6,
                labelWidth: 'auto',
                defaultCollapsed: false,
              }}
              pagination={{
                defaultPageSize: 10,
                showSizeChanger: true,
                showQuickJumper: true,
                showTotal: (total, range) =>
                  `共 ${total} 项数据，当前显示第 ${range[0]}-${range[1]} 项`,
              }}
              scroll={{ x: 1000 }}
              size="small"
              options={{
                density: false,
                reloadIcon: (
                  <AButton icon={<ReloadOutlined />} key="reload">
                    刷新
                  </AButton>
                ),
                setting: {
                  draggable: true,
                  checkable: true,
                  showListItemOption: true,
                  settingIcon: <AButton icon={<SettingOutlined />}>设置</AButton>,
                  listsHeight: 400,
                },
              }}
              toolBarRender={() => [
                <AButton
                  key="add"
                  icon={<PlusOutlined />}
                  type="primary"
                  onClick={() => {
                    form.resetFields();
                    setCurrentRecord({});
                    setDrawerType('ADD');
                    setDrawerShow(true);
                    form.setFieldsValue({
                      status: EnableStatusType.ENABLED.value, // 默认状态为启用
                    });
                  }}
                >
                  新增
                </AButton>,
              ]}
              locale={TableLocalePresets.product(actionRef)}
            />
          </div>
        </div>
      </div>
    </div>
  );
};

export default SystemRole;
